package com.huluobo.a2202monthdemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2202monthdemo.MainActivity
import com.huluobo.a2202monthdemo.R
import com.huluobo.a2202monthdemo.databinding.ActivityLoginBinding
import com.huluobo.base.db.AppDBUtils
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding>() {
    private lateinit var viewModel: LoginViewModel
    override fun initData() {
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]

        viewModel.loginSuccess.observe(this) {
            if (it.code == 200) {
                SPUtils.getInstance().put(Const.PARAM_TOKEN, it.data.token)
                ToastUtils.showLong("欢迎回来:${it.data.username}")
                SPUtils.getInstance().put(Const.PARAM_USERNAME, it.data.username)
                AppDBUtils.getDb().getUserInfoDao().insertUserInfo(it.data)
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.loginFailed.observe(this) {
            Log.i("TagA", "登录失败:$it")
        }
    }

    override fun initView() {
        dataBinding.loginToLoginBtn.setOnClickListener {
            if (!TextUtils.isEmpty(dataBinding.loginUsernameEt.text.toString())
                && !TextUtils.isEmpty(dataBinding.loginPasswordEt.text.toString())
            ) {
                viewModel.login(
                    dataBinding.loginUsernameEt.text.toString(),
                    dataBinding.loginPasswordEt.text.toString()
                )
            } else {
                ToastUtils.showLong("请输入用户米或者密码")
            }
        }

    }

    override fun getLayoutId(): Int = R.layout.activity_login
}